package com.nx.platform.es.biz.query.search.handler;

import com.google.common.base.Preconditions;
import com.nx.platform.es.biz.query.search.SearchRequestContext;
import com.nx.platform.es.biz.wrapper.parser.StatementOperator;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.math.NumberUtils;

import java.util.List;

/**
 * @author
 * @since 2016年10月15日
 */
public enum SearchPageHandler implements SearchRequestHandler {

    INSTANCE;

    private static final int DEFAULT_FROM = 0;
    private static final int DEFAULT_SIZE = 10;
    private static final int MAX_WINDOW_SIZE = 5000;

    @Override
    public void handle(SearchRequestContext context) {
        Preconditions.checkNotNull(context.getQueryTable());
        int from = getInt(context, "from");
        int size = getInt(context, "size");
        int page = getInt(context, "page");
        // size check
        size = size < 0 ? DEFAULT_SIZE : size;
        // page -> from
        if (page > 0 && from < 0) {
            from = size * (page - 1) + 1;
        }
        // from check
        from = from <= 0 ? DEFAULT_FROM : from - 1;
        // deep check
        if (from + size > MAX_WINDOW_SIZE) {
            from = DEFAULT_FROM;
            size = DEFAULT_SIZE;
        }
        context.getRequest().source().from(from).size(size);
        StringBuilder builder = context.getTrace();
        builder.append("&from=");
        builder.append(from);
        builder.append("&size=");
        builder.append(size);
    }

    private int getInt(SearchRequestContext context, String key) {
        List<String> list = context.getQueryTable().get(key, StatementOperator.EQUAL);
        if (CollectionUtils.isNotEmpty(list)) {
            return NumberUtils.toInt(list.get(0));
        } else {
            return -1;
        }
    }

}
